<?php

class CController extends Controller {

    public $model_name     = "";
    protected $sess_cont_alerts = 'controller_alerts';
    public function  __construct($vars) {
        parent::__construct($vars);
        if($this->model_name != "") $this->LoadModel($this->model_name, "model");
        if(!isset($_REQUEST['ajax'])){
            $this->registerVar("model", $this->model_name);
            $this->registerVar("component", LINK);
        }
    }
    
    protected $cod  = "";
    protected $item = array();
    protected $free_cod = array('index', 'formulario');
    protected $blocked_actions = array();
    protected function addToFreeCod($action){
        $this->free_cod[] = $action;
    }

    private function checkUrl(){
        if(in_array(CURRENT_ACTION, $this->blocked_actions)){
            if(!in_array("index", $this->blocked_actions)) Redirect(LINK);
            else Redirect ('');
        }
    }
    public function AfterLoad(){
        //inicializa as variáveis
        $this->checkUrl();
        
        //gerencia as sessions
        $this->cod  = isset($this->vars[0])?$this->vars[0]:"";
        if(in_array(CURRENT_ACTION, $this->free_cod)&& isset($_SESSION[LINK])) unset($_SESSION[LINK]);
        elseif($this->cod != "")$_SESSION[LINK] = $this->cod;
        elseif(isset($_SESSION[LINK])) Redirect(CURRENT_URL ."/".$_SESSION[LINK]);
        
        
        if($this->cod != "" && !in_array(CURRENT_ACTION, $this->free_cod)){
            if(method_exists($this->model, 'getItem')){
                $this->item = $this->model->getItem($this->cod, "", true);
                if(empty($this->item)){
                    $vars['erro'] = "Este item já foi apagado ou nunca existiu!";
                    $vars['status'] = "0";
                    Redirect (LINK, 0 , "", $vars);
                }
                
                //restaura as sessions
                $this->model->restoreSession($this->item);
            }
        }
            
        //gera as tags
        if(!empty ($this->item)){
            $dados = $this->model->getDados();
            $resumo = $titulo = "";
            foreach($this->item as $name => $arr){
                if(!array_key_exists($name, $dados)) continue;

                $arr = $dados[$name];
                if(!array_key_exists('seo', $arr)) continue;
                if(array_key_exists("titulo", $arr['seo']) && $titulo == "") $titulo = $this->item[$name];
                if(array_key_exists("resumo", $arr['seo']) && $resumo == "") $resumo = $this->item[$name];
            }
            $this->genTags($titulo , $resumo, str_replace(" ", " ,", $titulo));
            $this->genImageTag($this->item);
        }

        if(!isset($_REQUEST['ajax'])){$this->registerVar("item", $this->item);}
        
        if(cookie::cookieExists($this->sess_cont_alerts)){
            $this->setVars(cookie::getVar($this->sess_cont_alerts));
            cookie::destroy($this->sess_cont_alerts);
        }
    }

    
    public function getIndexListType(){
        return "listar";
    }
    
    public function index($display = true, $link = ""){
        $link = ($link == "")? "admin/auto/areacliente/page":$link;
        $this->setPage();
        if($this->getTag('page_title') == ""){
            $this->genTags(CURRENT_MODULE ." ", CURRENT_MODULE);
        }
        
        $item = $this->model->paginate($this->page, CURRENT_PAGE);
        if(empty($item)){
            $this->LoadModel('usuario/perfil/perfilPermissions', 'pperm');
            $this->pperm->RedirectIfHasPermission(LINK. "/formulario");
        }
        $this->registerVar("item"        , $item);
        $this->registerVar("comp_action" , $this->getIndexListType());
        $this->registerVar("show_links"  , '');
    	if($display) $this->display($link);
    }
    
    public function show($display = true, $link = ""){
        $link = ($link == "")? "admin/auto/areacliente/page":$link;
        $this->registerVar("comp_action" , 'show');
    	if($display) $this->display($link);
    }
    
    public function formulario($display = true, $link = ""){
        $desc = $this->model->getModelDescription();
        if($desc != "") EventTube::addEvent('body-top', "<div class='container-msg info'>$desc</div>");
        $this->forms($display, $link);
    }
    
    public function edit($display = true, $link = ""){
       $this->forms($display, $link);
    }

    public function apagar(){
        if($this->cod == "")Redirect(LINK);
        if($this->model->apagar($this->cod)){
            $vars = $this->model->getMessages();
            cookie::setVar($this->sess_cont_alerts, $vars);
            $vars['status'] = "1";
            $this->registerVar('status', '1');
            if(isset($_SESSION[LINK])) unset($_SESSION[LINK]);
            if(!$this->prevent_red) Redirect(LINK, 0, "", $vars);
            return;
        }

        $this->setVars($this->model->getMessages());
        $this->registerVar('status', "0");
        $this->genTags("Apagar Dados");
        $this->show();
    }
    
    public function sublist(){
        
        if(!isset($this->vars[1])) Redirect (LINK."/show");
        $page  = isset($this->vars[2])?$this->vars[2]:0;
        $campo = $this->vars[1];
        
        $link = $this->model_name ."/sublist/$this->cod/$campo";
        $this->item[$campo] = $this->model->getSublist($page, $campo, $link);
        
        $dados = $this->model->getDados();
        foreach($dados as $nm => $dd){
            if($nm == $campo) continue;
            if(!isset($dd['fkey'])) continue;
            if(!$dd['fkey']['cardinalidade'] != "n1") continue;
            if(isset($this->item[$name])) unset($this->item[$name]);
        }
        
        //print_r($this->item);die();
        if($this->item[$campo]  === false) Redirect (LINK."/show");
        $this->registerVar("item", $this->item);
        $this->registerVar("comp_action" , 'show');
    	$this->display("admin/auto/areacliente/page");
        //$this->display("admin/auto/areacliente/page");
    }
    
    public function group(){
        $arr = ($this->model->getCategorizedRow());
        if($arr != ""){
            $model = $arr['fkey']['model'];
            $cod_cat = isset($_SESSION[$model])?$_SESSION[$model]:"";
            if($cod_cat != ""){
                Redirect ("$model/$cod_cat");
            }
            
            if(!empty($this->item)){
                Redirect ("$model/".$this->item[$arr['name']]);
            }
        }
        
        Redirect(CURRENT_MODULE);
    }
    
    public function hasOwn(){
        $row = $this->model->getAltenticationRow();
        if($row == "") {return true;}
        if(empty($this->item)){return true;}
        $this->LoadModel('usuario/login', 'uobj');
        $cod = $this->uobj->getCodUsuario();
        if(!$this->item[$row] == $cod){return false;}
        return true;
    }
    
    private $prevent_red = false;
    protected function prevent_redirect(){
        $this->prevent_red = true;
    }
    protected function forms($display = true, $link = ""){
        $link = ($link == "")? "admin/auto/formulario":$link;
        if($this->getTag('page_title') == ""){
            $nome = (CURRENT_CONTROLLER == 'index')?CURRENT_MODULE:CURRENT_CONTROLLER;
            $nome = (($this->cod == "")? "Criar ":"Editar ") . $nome;
            $this->genTags(ucfirst($nome));
        }
        
        $this->registerVar('titulo', $this->getTag('page_title'));
        if(!empty($_POST)){
            $lastid = "";
            if($this->cod != ""){ $status = $this->model->editar($this->cod, $_POST); }
            else                { $status = $this->model->inserir($_POST); $lastid = $this->model->getLastId();}
            
            $messages = $this->model->getMessages();
            $vars = $messages;
            $vars['status'] = ($status == true)? 1:0;
            $this->setVars($vars);
            if($status == true && !$this->prevent_red){
                cookie::setVar($this->sess_cont_alerts, $messages);
                if($this->cod == ""){ Redirect(LINK."/show/$lastid"   , 0, "", $vars);}
                else                { Redirect(LINK."/show/$this->cod", 0, "", $vars);}
            }
        }
        
        if(!array_key_exists('ajax', $_REQUEST) || !$_REQUEST['ajax']){
            $this->registerVar('dados', $this->model->getDados());
            $formulario = ($this->cod == "")?"":$this->model->getItem($this->cod);
            $this->registerVar('values', $formulario);
        }
        if($display) $this->display($link);
    }
    
    protected function redirect($page){
        $dados = $this->model->getMessages();
        foreach($this->variaveis as $name => $var) $dados[$name] = $var;
        cookie::setVar($this->sess_cont_alerts, $dados);
        Redirect($page, 0, "", $dados);
    }
}
?>